package com.wsk.api.impl;

import com.wsk.api.bean.User;
import com.wsk.api.bean.UserEnum;
import com.wsk.api.factory.UserFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;

/**
 * @DESCRIPTION :
 * @AUTHOR : WuShukai1103
 * @TIME : 2017/12/9  22:03
 */
public class SuperUserLoginImpl {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserFactory userFactory;

    //    public AdminUserLoginImpl(){
//
//        JedisPool jedisPool = new JedisPool();
//        jedis = jedisPool.getResource();
//    }
    public User login(User user) {
        try {
            if (StringUtils.isNotBlank(user.getId())) {
                String id = redisTemplate.opsForValue().get("String_" + user.getId());
                if (StringUtils.isNotBlank(id)) {
                    String password = (String) redisTemplate.opsForHash().get(user.getId(), "password");
                    if (user.getPassword().equals(password)) {
                        Map<Object, Object> map = redisTemplate.opsForHash().entries(id);
                        UserEnum userEnum = Enum.valueOf(UserEnum.class, (String) map.get("userenum"));
                        user = userFactory.getUser(userEnum);
                        user.setPassword((String) map.get("password"));
                        user.setName((String) map.get("name"));
                        user.setId(id);
                        user.setUserEnum(userEnum);
                        return user;
                    } else {
                        return null;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }
}
